package com.fyzk.activity.fragment;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.app.App;
import com.fyzk.activity.lottery.basketball.JCLQFragmentActivityI;
import com.fyzk.activity.lottery.jc.football.newJz.FootballFragmentActivityI;
import com.fyzk.activity.lottery.recommend_order.MyRecommendOrderActivity;
import com.fyzk.activity.lottery.recommend_order.OtherCenterActivity;
import com.fyzk.activity.lottery.recommend_order.RankBean;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.adapter.DocumentaryMenuAdapter;
import com.fyzk.adapter.DocumentaryPagerAdapter;
import com.fyzk.base.BaseFragment;
import com.fyzk.bean.DocumentaryMenuResponse;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.manager.UIManager;
import com.fyzk.model.DocumentaryViewModel;
import com.fyzk.net.Commands;
import com.fyzk.utils.AssetsUtil;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.StringUtils;
import com.fyzk.view.TabLayoutUnderline;
import com.fyzk.view.ViewCallBack;
import com.fyzk.view.dropdowntablayout.DropdownTabLayout;
import com.tyjc.lottery.R;
import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionButton;
import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionHelper;
import com.wangjie.rapidfloatingactionbutton.RapidFloatingActionLayout;
import com.wangjie.rapidfloatingactionbutton.contentimpl.labellist.RFACLabelItem;
import com.wangjie.rapidfloatingactionbutton.contentimpl.labellist.RapidFloatingActionContentLabelList;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * @author yangfeng
 * @create 跟单界面
 * @Describe
 */
@ContentView(R.layout.fragment_root_documentary)
public class DocumentaryRootFragment extends BaseFragment {
    @ViewInject(R.id.documentary_rv_menu)
    RecyclerView mDocumentaryMenu;
    @ViewInject(R.id.documentary_tb)
    DropdownTabLayout mDocumentaryTab;
    @ViewInject(R.id.documentary_vp_classify)
    ViewPager mVpDocumentary;
    @ViewInject(R.id.mFloatingLayout)
    private RapidFloatingActionLayout mFloatingLayout;
    @ViewInject(R.id.mFloating)
    RapidFloatingActionButton mFloatActionView;
    @ViewInject(R.id.ll_no1)
    LinearLayout mLlNo1;
    @ViewInject(R.id.iv_avatar_no1)
    ImageView mIvAvatarNo1;
    @ViewInject(R.id.tv_name_no1)
    TextView mTvNameNo1;
    @ViewInject(R.id.tv_red_no1)
    TextView mTvRedNo1;
    @ViewInject(R.id.ll_no2)
    LinearLayout mLlNo2;
    @ViewInject(R.id.iv_avatar_no2)
    ImageView mIvAvatarNo2;
    @ViewInject(R.id.tv_name_no2)
    TextView mTvNameNo2;
    @ViewInject(R.id.tv_red_no2)
    TextView mTvRedNo2;
    @ViewInject(R.id.ll_no3)
    LinearLayout mLlNo3;
    @ViewInject(R.id.iv_avatar_no3)
    ImageView mIvAvatarNo3;
    @ViewInject(R.id.tv_name_no3)
    TextView mTvNameNo3;
    @ViewInject(R.id.tv_red_no3)
    TextView mTvRedNo3;
    @ViewInject(R.id.tv_look_more)
    TextView mTvLookMore;
    private DocumentaryMenuAdapter mMenuAdapter;
    private GridLayoutManager mMenuGridLayoutManager;
    private List<Fragment> mFragmentList = new ArrayList<>();
    private List<RankBean> rankList = new ArrayList<>();

    private DocumentaryViewModel mDocumentaryViewModel;

    private RapidFloatingActionHelper rfabHelper;

    public static DocumentaryRootFragment newInstance() {

        Bundle args = new Bundle();

        DocumentaryRootFragment fragment = new DocumentaryRootFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return x.view().inject(this, inflater, container);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        initViewPager();
        initMenuClick();
    }

    private void initMenuClick() {
        mDocumentaryMenu.addOnItemTouchListener(getListener());
        mTvLookMore.setOnClickListener(this);
        mLlNo1.setOnClickListener(this);
        mLlNo2.setOnClickListener(this);
        mLlNo3.setOnClickListener(this);
    }

    @NonNull
    private OnItemClickListener getListener() {
        return new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (!(position == mMenuAdapter.getCurrentIndex())) {
                    mMenuAdapter.setCurrentIndex(position);
                    findNewRecommendOrders(true, mMenuAdapter.getCurrentItem().getType());
                }
            }
        };
    }

    /**
     * 初始化数据
     */
    private void initView() {
        initFloatActionView();
        mMenuGridLayoutManager = new GridLayoutManager(getActivity(), 3);
        mDocumentaryMenu.setLayoutManager(mMenuGridLayoutManager);
        mMenuAdapter = new DocumentaryMenuAdapter();
        mDocumentaryMenu.setAdapter(mMenuAdapter);
        List<DocumentaryMenuResponse> mMenuListData = new ArrayList<>();
        try {
            String mMenuData = AssetsUtil.read(getActivity(), "json/documentaryMenuNew.json");
            mMenuListData = JSON.parseObject(mMenuData, new TypeReference<List<DocumentaryMenuResponse>>() {
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        mMenuAdapter.setNewData(mMenuListData);

        findNewRecommendOrders(true, mMenuAdapter.getCurrentItem().getType());
    }

    /**
     * 查询晒单大厅 最新推荐
     *
     * @param showProgress
     */
    private void findNewRecommendOrders(boolean showProgress, int type) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("raceType", type);    // 类型（=1连红榜，=2命中榜，=3盈利榜，=4人气榜）
            httpPostJson(CommandUtil.FINDRECOMMENDPOWERRANKING, Commands.FINDRECOMMENDPOWERRANKING, request_json,
                    showProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        List<RankBean> beans = JSON.parseArray(resultBean.getData(), RankBean.class);
        showRankData(beans);
    }

    @Override
    public void onFailure(int requestCode, String errorCode, String message) {
        showRankData(null);
    }


    @Override
    protected void onFailure(int requestCode, String message) {
        super.onFailure(requestCode, message);
        showRankData(null);
    }

    /**
     * 展示排行榜信息
     *
     * @param list
     */
    private void showRankData(List<RankBean> list) {
        if (list == null)
            return;
        rankList.clear();
        rankList.addAll(list);
        for (int i = 0; i < rankList.size(); i++) {
            DocumentaryMenuResponse menuItem = mMenuAdapter.getCurrentItem();
            if (menuItem == null)
                return;
            RankBean item = rankList.get(i);
            String redText = "0";
            try {
                switch (menuItem.getType()) {
                    case 1://连红榜
                        redText = String.format("%s连红", item.getEvenRed());
                        break;
                    case 2://命中榜
                        redText = String.format("%.2f%%", item.getHitRatio() * 100);
                        break;
                    case 3://盈利榜
                        redText = String.format("%.2f%%", Double.parseDouble(item.getProfitRatio()) * 100);
                        break;
                    case 4://人气榜
                        redText = String.valueOf(item.getPopularity());
                        break;
                }
            } catch (NumberFormatException e) {
            }
            switch (i) {
                case 0://第一名
                    Glide.with(getContext())
                            .load(item.getUserPhotoUrl())
                            .circleCrop()
                            .error(R.drawable.rr_header_icon)
                            .placeholder(R.drawable.rr_header_icon)
                            .into(mIvAvatarNo1);
                    mTvNameNo1.setText(StringUtils.formatBindMobile(item.getUserName()));
                    mTvRedNo1.setText(redText);
                    break;
                case 1://第二名
                    Glide.with(getContext())
                            .load(item.getUserPhotoUrl())
                            .circleCrop()
                            .error(R.drawable.rr_header_icon)
                            .placeholder(R.drawable.rr_header_icon)
                            .into(mIvAvatarNo2);
                    mTvNameNo2.setText(StringUtils.formatBindMobile(item.getUserName()));
                    mTvRedNo2.setText(redText);
                    break;
                case 2://第三名
                    Glide.with(getContext())
                            .load(item.getUserPhotoUrl())
                            .circleCrop()
                            .error(R.drawable.rr_header_icon)
                            .placeholder(R.drawable.rr_header_icon)
                            .into(mIvAvatarNo3);
                    mTvNameNo3.setText(StringUtils.formatBindMobile(item.getUserName()));
                    mTvRedNo3.setText(redText);
                    return;
            }
        }
    }

    private void initFloatActionView() {
        RapidFloatingActionContentLabelList rfaContent = new RapidFloatingActionContentLabelList(getActivity());
        List<RFACLabelItem> items = new ArrayList<>();
        items.add(new RFACLabelItem<Integer>()
                .setLabel(getResources().getString(R.string.jcz))
                .setResId(R.drawable.icon_football)
                .setIconNormalColor(0xffd84315)
                .setIconPressedColor(0xffbf360c)
                .setWrapper(0)
                .setLabelBackgroundDrawable(null)
        );
        items.add(new RFACLabelItem<Integer>()
                .setLabel(getResources().getString(R.string.jclq))
                .setResId(R.drawable.icon_basketball)
                .setIconNormalColor(0xff4e342e)
                .setIconPressedColor(0xff3e2723)
                .setWrapper(1)
        );
        items.add(new RFACLabelItem<Integer>()
                .setLabel(getResources().getString(R.string.my_center))
                .setResId(R.drawable.icon_my_center)
                .setIconNormalColor(0xff4e342e)
                .setIconPressedColor(0xff3e2723)
                .setWrapper(2)
        );
        rfaContent
                .setItems(items)
                .setOnRapidFloatingActionContentLabelListListener(new RapidFloatingActionContentLabelList.OnRapidFloatingActionContentLabelListListener() {
                    @Override
                    public void onRFACItemLabelClick(int position, RFACLabelItem item) {
                        rfabHelper.toggleContent();
                        dispatcherFloatItemClick(position, item);
                    }

                    @Override
                    public void onRFACItemIconClick(int position, RFACLabelItem item) {
                        rfabHelper.toggleContent();
                        dispatcherFloatItemClick(position, item);
                    }
                });
        ;
        rfabHelper = new RapidFloatingActionHelper(
                getActivity(),
                mFloatingLayout,
                mFloatActionView,
                rfaContent
        ).build();
    }

    private void dispatcherFloatItemClick(int position, RFACLabelItem item) {
        Object wrapper = item.getWrapper();
        if (wrapper instanceof Integer) {
            switch ((int) wrapper) {
                case 0://竞彩足球
                    App.isBaskOrder = true;
                    Intent footIntent = new Intent(getActivity(), FootballFragmentActivityI.class);
                    startActivity(footIntent);
                    break;
                case 1://竞彩篮球
                    App.isBaskOrder = true;
                    Intent basketIntent = new Intent(getActivity(), JCLQFragmentActivityI.class);
                    startActivity(basketIntent);
                    break;
                case 2://我的中心
                    Intent intent = new Intent(getActivity(), OtherCenterActivity.class);
                    intent.putExtra(IntentParamUtils.USERNO, MySharedPreferences.getInstance().getUserNo());
                    startActivity(intent);
                    break;
            }
        }
    }

    /**
     * 初始化ViewPager
     */
    private void initViewPager() {
        List<List<DocumentaryMenuResponse>> mTabData;
        String mTabDataStr = AssetsUtil.read(getActivity(), "json/documentaryTab.json");
        mTabData = JSON.parseObject(mTabDataStr, new TypeReference<List<List<DocumentaryMenuResponse>>>() {
        });
        for (int i = 0; i < mTabData.size(); i++) {
            List<DocumentaryMenuResponse> itemTabs = mTabData.get(i);
            if (null != itemTabs && !itemTabs.isEmpty()) {
                DocumentaryFragment fragment = DocumentaryFragment.newInstance(itemTabs.get(0).getId());
                mFragmentList.add(fragment);
            }
        }
//        AttentionGodFragment attentionGodFragment = AttentionGodFragment.newInstance(mTabData.get(2).getId());
//        mFragmentList.add(attentionGodFragment);
        DocumentaryPagerAdapter mDocumentaryPagerAdapter = new DocumentaryPagerAdapter(getChildFragmentManager(), mFragmentList);
        mVpDocumentary.setAdapter(mDocumentaryPagerAdapter);
        mVpDocumentary.setOffscreenPageLimit(mTabData.size());
        mDocumentaryTab.setupWithViewPager(mVpDocumentary);
        mDocumentaryTab.setUpTitle(mTabData);
        TabLayoutUnderline.setTabLayoutIndicator(mDocumentaryTab);
        mDocumentaryViewModel = ViewModelProviders.of(getActivity()).get(DocumentaryViewModel.class);
        mDocumentaryViewModel.getLoginLiveData().observe(getActivity(), new Observer<Integer>() {
            @Override
            public void onChanged(@Nullable Integer integer) {
                if (null != mVpDocumentary && null != mDocumentaryTab) {
                    mVpDocumentary.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mVpDocumentary.setCurrentItem(0);
                            mDocumentaryTab.getTabAt(0).select();
                        }
                    }, 200);
                }
            }
        });

        mDocumentaryTab.setmOnTabSelectedListener((tabPosition, listPosition) -> {
            if (tabPosition < mFragmentList.size() && tabPosition < mTabData.size()) {
                Fragment fragment = mFragmentList.get(tabPosition);
                List<DocumentaryMenuResponse> list = mTabData.get(tabPosition);
                if (listPosition < list.size()) {
                    DocumentaryMenuResponse documentaryMenuResponse = list.get(listPosition);
                    if (fragment instanceof DocumentaryFragment)
                        ((DocumentaryFragment) fragment).setNewType(documentaryMenuResponse.getId());
                }
            }
        });

    }

    @Override
    public void onRightClick() {
        super.onRightClick();
        Intent intent;
        if (!MySharedPreferences.getInstance().getLoginStatus()) {
            AppLotteryInfos.clear();
            ViewCallBack.getInstance().countDownObjs.clear();
            ActivityTaskManager.getInstance().closeAllActivity();
            intent = new Intent(getContext(), LoginActivity.class);
        } else {
            intent = new Intent(getContext(), MyRecommendOrderActivity.class);
        }
        startActivity(intent);
    }

    @Override
    public void onLeftClick() {
        super.onLeftClick();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_look_more://查看全部榜单
                DocumentaryMenuResponse item = mMenuAdapter.getCurrentItem();
                if (item == null)
                    return;
                Bundle bundle = new Bundle();
                bundle.putInt("index", item.getId());
                UIManager.startActivityByUri(getActivity(), item.getAction(), bundle);
                break;
            case R.id.ll_no1://第一名
                startOtherCenterActivity(0);
                break;
            case R.id.ll_no2://第二名
                startOtherCenterActivity(1);
                break;
            case R.id.ll_no3://第三名
                startOtherCenterActivity(2);
                break;
        }
    }

    /**
     * 打开他的中心
     *
     * @param index
     */
    private void startOtherCenterActivity(int index) {
        if (rankList.size() <= index)
            return;
        RankBean item = rankList.get(index);
        Intent intent = new Intent(getContext(), OtherCenterActivity.class);
        if (null != item) {
            intent.putExtra(IntentParamUtils.USERNO, item.getUserno());
            startActivity(intent);
        }
    }
}
